const kingdeeAllApis = require('../../libs-jdy/openapi/kingdeeAllApi');
const kingdeeAuthToken = require('../../libs-jdy/openapi/kingdeeAuthToken');
const logAppRepository = require('../repository/log-app-repository');
const redisUtil = require('../libs/redis-util');

/**
 * 原生接口调用
 */
const kingdeeApi = async (ctx) => {
    const params = ctx.request.body;
    const {kingdeeurl} = ctx.request.headers;
    const {zlzouterinstanceid} = ctx.request.headers;
    let resData;
    let method = ctx.method;
    let pushAppAuthorizeList;
    let data = {
        outerInstanceId: zlzouterinstanceid
    }
    await Promise.resolve().then(async () => {
        try {
            const accountData = await logAppRepository.getAccountAppCount(data);
            resData = await redisUtil.get(`jwt:${data.outerInstanceId}:pushAppAuthorizeList`);
            if (!resData) {
                let kingdeeData = {
                    clientID: accountData.clientId,
                    clientSecret: accountData.clientSecret,
                    appKey: accountData.appKey,
                    outerInstanceId: accountData.outerInstanceId,
                }
                const auth = new kingdeeAuthToken(kingdeeData);
                const {pushAppAuthorizeList, appTokenList} = await auth.getAppToken();
                pushAppAuthorizeList.app_token = appTokenList['app-token'];
                pushAppAuthorizeList.access_token = appTokenList.access_token;
                pushAppAuthorizeList.clientSecret = kingdeeData.clientSecret;
                await redisUtil.set(`jwt:${data.outerInstanceId}:pushAppAuthorizeList`, JSON.stringify(pushAppAuthorizeList), 9000);
            } else {
                pushAppAuthorizeList = JSON.parse(resData);
            }
            const kingdeeAllApi = new kingdeeAllApis(pushAppAuthorizeList.clientId, pushAppAuthorizeList.clientSecret, pushAppAuthorizeList.app_token);
            const kingdeeAllApiRes = await kingdeeAllApi.allOpenApi(params, params, kingdeeurl, method);
            ctx.body = Res.success(kingdeeAllApiRes);
        } catch (error) {
            ctx.body = Res.error("接口返回失败", {
                code: error.response.data.errcode,
                message: error.response.data.description
            });
        }

    })
}
module.exports = {
    kingdeeApi
};